package priv.bestbeat.reportcenter.worker.consumer.rocket;

import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import priv.bestbeat.reportcenter.core.exception.ConsumeException;
import priv.bestbeat.reportcenter.core.monitor.TaskObservable;
import priv.bestbeat.reportcenter.core.mq.MessageProxy;
import priv.bestbeat.reportcenter.core.mq.rocket.RocketMessage;
import priv.bestbeat.reportcenter.core.task.OfflineTask;
import priv.bestbeat.reportcenter.core.task.states.TaskStateEnum;

import javax.annotation.Resource;

/**
 * @author 张渠钦
 * @date 2022/4/28 10:50
 */
@Component
@RocketMQMessageListener(consumerGroup = "Gtest",topic = "taskA",selectorType = SelectorType.TAG,selectorExpression = "*",
        consumeMode = ConsumeMode.CONCURRENTLY,messageModel = MessageModel.CLUSTERING,maxReconsumeTimes = 3)
public class OfflineTaskConsumer implements RocketMQListener<TaskObservable<OfflineTask>> {

    @Resource
    private MessageProxy messageProxy;

    private int errorHappen = 0;

    @Override
    public void onMessage(TaskObservable<OfflineTask> message) {
        RocketMessage<TaskObservable> replyMessage = new RocketMessage<>();

        try {
            /*
            执行逻辑
             */
            if (errorHappen == 2) {
                throw new ConsumeException();
            }
            errorHappen++;
            message.setState(TaskStateEnum.DONE);
        } catch (Exception e) {
            message.setState(TaskStateEnum.TRY_AGAIN);
            throw new ConsumeException();
        } finally {

            replyMessage.setTopic("taskReply");
            replyMessage.setTags("tag1");
            replyMessage.setPayload(message);
            try {
                messageProxy.send(replyMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
